#!/usr/bin/python
#
# Copyright (C) 2009 rambla.be
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

""" Simple cli script to POST a file to a given location on the RASS server. 
>> python rasspostcli.py options
"""

import os, sys, optparse
import rawsc
import rawsc.service
from rawsc import rass
import rawsc.rass.service

# do some logging, change the location of the logfile for your local machine
import logging
hdlr = logging.FileHandler(filename = "/data/local/log/raws/rasspostcli.log", mode = 'a')
hdlr.setFormatter(logging.Formatter('[%(asctime)s]%(levelname)-8s"%(message)s"','%Y-%m-%d %a %H:%M:%S'))
hdlr.setLevel(logging.INFO)
logging.root.addHandler(hdlr)

def main():
    p = optparse.OptionParser()
    p.add_option('-s', '--svr', dest = "svr", help = "Service base uri (e.g. 'rass.cdn01.rambla.be')")
    p.add_option('-u', '--user', dest = "user", help = "User account name")
    p.add_option('-p', '--pwd', dest = "pwd", help = "User account password")
    p.add_option('-d', '--dir', dest = "dir", help = "Path (starting from the user's CDN rootdir) to the directory.")
    p.add_option('-f', '--file', dest = "file", help = "Filename, including extension.")
    p.add_option('-l', '--location', dest = "location", help = "Local path to the file that needs to be posted.")
    options, arguments = p.parse_args()
    logging.info("Starting new POST, options follow..")
    logging.info(str(options))
    if options.user is None:
        print "No user provided."
        logging.error("No user provided.")
        sys.exit(3)
    if options.pwd is None:
        print "No pwd provided."
        logging.error("No pwd provided.")
        sys.exit(3)
    if options.dir is None:
        print "No dir provided."
        logging.error("No dir provided.")
        sys.exit(4)
    if options.file is None:
        print "No file provided."
        logging.error("No file provided.")
        sys.exit(5)
    if options.location is None:
        print "No location provided."
        logging.error("No location provided.")
        sys.exit(6)
    
    # execute the client
    try:
        # Create a Rass instance, passing it your login credentials and the base service uri
        client = rawsc.rass.service.RassService(username=options.user, password=options.pwd, server=options.svr)
        entry = client.postItem(dirpath = options.dir, filename = options.file, local_path = options.location)
        print str(entry.content.params.name.text) # filename returned by POST
    except rawsc.service.Error, e:
        error_dict = e[0] # error dict inside the first tuple elem
        print "RASS responded with HTTP status code " + str(error_dict["status"])
        logging.error("POST failed with these parameters: svr = %s, user = %s, dir = %s, file = %s, location = %s" % (options.svr, options.user, options.dir, options.file, options.location))
        logging.error("HTTP status code: %s" % str(error_dict["status"]))
        if error_dict.has_key("body"):
            logging.error("RASS response body: %s" % str(error_dict["body"]))
        sys.exit(1)
    except rawsc.RawscException, e:
        print "RawscException caught, reason = %s." % str(e)
        sys.exit(7)
    except StandardError, e:
        print "StandardError caught, reason = %s." % str(e)
        sys.exit(8)
    except:
        print "unhandled exception caught"
        sys.exit(9)

    sys.exit(0)

if __name__ == '__main__':
    main()
